/**
 * 系统管理公用分页组件
 */

function Pagination(wrapper){
	var _tpl = require("./pagination.hbs");
	var $wrapper = $(wrapper);
	$wrapper.append(_tpl);

	this.lock = true;
	this.nodes = {
		$wrapper: $wrapper,
		$pre: $wrapper.find('.pre'),
		$next: $wrapper.find('.next'),
		$active: $wrapper.find('.active'),
		$total: $wrapper.find('.total')
	};
	this.params = {
		page: 1,
		pageSize: 10,
		keyWord: ''
	};
	this.data = {
		total: 0, // 当前分页的数据量
		currentPage: 1 // 当前页码
	};
}

Pagination.prototype = {
	constructor : Pagination,
	init: function(total, $wrapper){
		this.bindBtn();

		this.lock = true;
		this.send();
	},

	getParams: function(){
		this.params.page = this.data.currentPage;
		return this.params;
	},

	clearLock: function(){
		this.lock = false;
	},

	// override, 需要在成功后手动解锁lock
	send: function(){
		
	},

	setTotal: function(total){
		this.data.total = total;
		this.maxPage = parseInt(this.data.total / this.params.pageSize);
		if(this.data.total % this.params.pageSize > 0) this.maxPage++;
		this.nodes.$total.html(this.maxPage);

		this.nodes.$wrapper.show();

		if(total == 0 || !total) this.nodes.$wrapper.hide();

		if(this.maxPage < this.params.page){//如果有删除分页的最后一页数据，分页需要重置为当前最大值
			this.params.page = this.maxPage;
			this.data.currentPage = this.params.page;
			this.nodes.$total.html(this.maxPage);
			this.nodes.$active.html(this.maxPage);
		}
	},

	bindBtn: function(){
		var scope = this;
		this.nodes.$pre.on('click', function(e){
			if(scope.data.currentPage==1 || scope.lock) return;
			scope.data.currentPage--;
			scope.setCurrentPageDom();
			scope.lock = true;
			scope.send();
		});
		this.nodes.$next.on('click', function(e){
			if(!scope.isHasNext() || scope.lock) return;
			scope.data.currentPage++;
			scope.setCurrentPageDom();
			scope.lock = true;
			scope.send();
		});
	},

	getCurrentPage: function(){
		return this.data.currentPage;
	},

	setCurrentPageDom: function(){
		this.nodes.$active.html(this.data.currentPage);
	},

	isHasNext: function(){
		if( this.maxPage > this.getCurrentPage() ) return true;
		else return false;
	},

	setPage: function(page){
		this.params.page = page;
	},
	setPageSize: function(pageSize){
		this.params.pageSize = pageSize;
	},
	setKeyWord: function(keyWord){
		this.params.keyWord = keyWord;
	},
	reset: function(){
		this.setPage(1);
		this.data.currentPage = 1;
		this.setCurrentPageDom();
	}
}

module.exports = Pagination;